package com.zz.bid.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zz.bid.exception.base.BidException;
import com.zz.bid.mapper.SettleFlowMapper;
import com.zz.bid.mapper.SettleMapper;
import com.zz.bid.pojo.entity.SettleFlowEnum;
import com.zz.bid.pojo.query.SettleQuery;
import com.zz.bid.pojo.to.SettleFlowDetails;
import com.zz.bid.pojo.to.SettlementDesc;
import com.zz.bid.util.ExcelUtil;
import com.zz.bid.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SettleService {

    @Autowired
    private SettleMapper settleMapper;

    @Autowired
    private SettleFlowMapper flowMapper;

    @Transactional(rollbackFor = BidException.class)
    public void create(SettlementDesc settlementDesc) throws BidException {
        //向数据库添加数据
        settleMapper.addSettlement(settlementDesc);
        //创建结算的目录
        for (SettleFlowEnum flowEnum : SettleFlowEnum.values()) {
            FileUtil.mkdir(FileUtil.getSettlePath(settlementDesc.getId(), flowEnum.getFlowName()));
        }
    }

    public PageInfo<SettlementDesc> getSettles(SettleQuery settleQuery) throws BidException {
        try {
            PageHelper.startPage(settleQuery.getPageNo(), settleQuery.getPageSize());
            System.out.println(">>>>>>" + settleQuery.getStartSignDate() + settleQuery.getEndSignDate());
            List<SettlementDesc> settles = settleMapper.getSettles(settleQuery);
            return new PageInfo<>(settles);
        } catch (Exception e) {
            throw new BidException(e.getMessage());
        }
    }

    public SettlementDesc getSettle(Integer settleId) throws BidException {
        try {
            return settleMapper.getSettle(settleId);
        } catch (Exception e) {
            throw new BidException(e.getMessage());
        }
    }

    public void update(SettlementDesc settlementDesc) throws BidException {
        try {
            settleMapper.update(settlementDesc);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BidException(e.getMessage());
        }
    }

    public byte[] loadfile(String fileName, int settleId, int flowId) throws BidException {
        try {
            String filePath = FileUtil.getSettlePath(settleId, SettleFlowEnum.values()[flowId].getFlowName());
            log.info(filePath);
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath + File.separator + fileName));
            byte[] bs = new byte[fis.available()];
            fis.read(bs);
            fis.close();
            return bs;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BidException(e.getMessage());
        }
    }

    @Transactional
    public void storeFile(int settleId, int flowId, String user, MultipartFile file) throws BidException {
        try {
            // update更新人和更新时间
            FileUtil.storeFile(file, FileUtil.getSettlePath(settleId, SettleFlowEnum.values()[flowId].getFlowName()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BidException(e.getMessage());
        }
    }

    public SettleFlowDetails getFlow(Integer settleId, Integer flowId) {
        SettleFlowDetails settleFlowDetails = flowMapper.getSettleFlow(settleId, flowId);
        List<String> flowFileNames = new ArrayList<>();
        String path = FileUtil.getSettlePath(settleId, SettleFlowEnum.values()[flowId].getFlowName());
        File fileDir = new File(path);
        File[] filelist = fileDir.listFiles();
        Assert.notNull(filelist, "file not valid");
        for (File file : filelist) {
            if (file.isFile()) {
                flowFileNames.add(file.getName());
            }
        }
        settleFlowDetails.setFileNames(flowFileNames);
        return settleFlowDetails;
    }

    @Transactional
    public void deleteSettleFile(Integer settleId, Integer flowId, String fileName, String user) throws BidException {
        try {
            String filePath = FileUtil.getSettlePath(settleId, SettleFlowEnum.values()[flowId].getFlowName());
            File file = new File(filePath + File.separator + fileName);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BidException(e.getMessage());
        }
    }

    public void delete(Integer settleId) throws BidException {
        try {
            settleMapper.logicDelete(settleId);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BidException(e.getMessage());
        }
    }

    public void updateForTechMan(SettlementDesc settle) throws BidException {
        try {
            settleMapper.updateForTechMan(settle);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BidException(e.getMessage());
        }
    }

    public void updateForCostMan(SettlementDesc settle) throws BidException {
        try {
            settleMapper.updateForCostMan(settle);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BidException(e.getMessage());
        }
    }

    public HSSFWorkbook export(SettleQuery settleQuery) {
        List<SettlementDesc> settles = settleMapper.getSettles(settleQuery);
        //excel标题
        String[] title = {"项目名称", "签订时间", "项目规模", "项目暂估价（元）", "项目结算金额（元）", "第一次到款金额（元"
                , "时间", "第二次到款金额（元）", "时间", "第三次到款金额（元）", "时间", "第一次劳务支出（元）", "时间",
                "第二次劳务支出（元）", "时间", "第三次劳务支出（元）", "时间", "报告打印费用（元）", "结算人员", "技术人员", "项目负责人"};
        //sheet名
        String sheetName = "结算信息表";
        String[][] content = new String[settles.size() + 1][title.length];
        for (int i = 0; i < settles.size(); i++) {
            SettlementDesc settlementDesc = settles.get(i);
            content[i][0] = settlementDesc.getName() + "";
            content[i][1] = settlementDesc.getSignDate();
            content[i][2] = settlementDesc.getScale();
            content[i][3] = settlementDesc.getValuation();
            content[i][4] = settlementDesc.getFinalDeposit();
            content[i][5] = settlementDesc.getFirstArriveMoney();
            content[i][6] = settlementDesc.getFirstArriveMoneyDate();
            content[i][7] = settlementDesc.getSecondArriveMoney();
            content[i][8] = settlementDesc.getSecondArriveMoneyDate();
            content[i][9] = settlementDesc.getThirdArriveMoney();
            content[i][10] = settlementDesc.getThirdArriveMoneyDate();
            content[i][11] = settlementDesc.getFirstLabor();
            content[i][12] = settlementDesc.getFirstLaborDate();
            content[i][13] = settlementDesc.getSecondLabor();
            content[i][14] = settlementDesc.getSecondLaborDate();
            content[i][15] = settlementDesc.getThirdLabor();
            content[i][16] = settlementDesc.getThirdLaborDate();
            content[i][17] = settlementDesc.getPrintCost();
            content[i][18] = settlementDesc.getSettleMan();
            content[i][19] = settlementDesc.getTechMan();
            content[i][20] = settlementDesc.getInCharge();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        return wb;
    }
}
